package br.ufes.inf.lprm.cwtools.entities.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.com.caelum.vraptor.ioc.ApplicationScoped;
import br.ufes.inf.lprm.cwtools.entities.Component;
import br.ufes.inf.lprm.cwtools.tools.JPAUtil;

@br.com.caelum.vraptor.ioc.Component
@ApplicationScoped
public class ComponentDAO {
	private EntityManager em;
	
	public ComponentDAO(JPAUtil ju) {
		this.em = ju.getEntityManager();
	}
	
	public void insert(Component dc) {
		try{
			em.getTransaction().begin();
			em.persist(dc);
			em.getTransaction().commit();
		}catch(Exception e){
			//do nothing
		}finally{
			if(em.getTransaction().isActive()){
				em.getTransaction().rollback();
			}
		}
	}
	
	public void update(Component dc) {
		try{
			em.getTransaction().begin();
			em.merge(dc);
			em.getTransaction().commit();
		}catch(Exception e){
			//do nothing
		}finally{
			if(em.getTransaction().isActive()){
				em.getTransaction().rollback();
			}
		}
	}
	
	public void delete(Component comp){
		delete(comp.getId());
	}
	
	public void delete(long id) {
		try{
			em.getTransaction().begin();
			em.remove(em.find(Component.class, id));
			em.getTransaction().commit();
		}catch(Exception e){
			//do nothing
		}finally{
			if(em.getTransaction().isActive()){
				em.getTransaction().rollback();
			}
		}
	}

	public Component find(Component component) {
		if(component.getId() != 0){
			return findById(component.getId());
		}else if(!component.getMd5hash().isEmpty()){
			return findByMd5hash(component.getMd5hash());
		}else{
			return null;
		}
	}
	
	public Component findById(long id) 
	{
		Component comp = null;
		
		try{
			em.getTransaction().begin();
			comp = em.find(Component.class, id);
			em.getTransaction().commit();
		}catch(Exception e){
			//do nothing
		}finally{
			if(em.getTransaction().isActive()){
				em.getTransaction().rollback();
			}
		}
		
		return comp;
	}
	
	public Component findByMd5hash(String md5hash) {
		Query q = em.createQuery("SELECT c FROM Component c WHERE c.md5hash = :compHash");
		q.setParameter("compHash", md5hash);
		return (Component) q.getSingleResult();
	}
	
	@SuppressWarnings("unchecked")
	public List<Component> listAll() {
		Query q = em.createQuery("SELECT c FROM Component c ORDER BY c.name ASC");
		return q.getResultList();
	}
}